import CodeMirror from '@uiw/react-codemirror';
import { monokaiInit } from "@uiw/codemirror-theme-monokai";
// import { javascript } from "@codemirror/lang-javascript";
import { sql } from '@codemirror/lang-sql';
import { json } from '@codemirror/lang-json';
import { keymap } from '@codemirror/view';
import { gotoLine } from '@codemirror/search';

import { useRef, forwardRef, useImperativeHandle } from 'react';
const langs = {
  sql,
  json
}
const CodeEditor = ({ value, onChange, height, lang, readOnly }, ref) => {
  const editorRef = useRef()
  const keymapExtension = keymap.of([
    {
      key: "Alt-g",
      run: (view) => {
        gotoLine(view)
        console.log(view)
        console.log("Save triggered!"); // Action to be taken when "Ctrl-s" is pressed
        return true; // Return true to indicate the key was successfully handled
      },
      preventDefault: true, // Prevents the default browser action for this key
    }
  ])


  useImperativeHandle(ref, () => ({
    getEditor: () => editorRef.current
  }))
  return (
    <CodeMirror
      ref={editorRef}
      readOnly={readOnly}
      value={value}
      height={height}
      extensions={[langs[lang](), keymapExtension]}
      onChange={onChange}
      theme={monokaiInit({
        settings: {
          background: '#002146',
          gutterBackground: '#002146',
        }
      })}
      lang={lang}
    />);
}

export default forwardRef(CodeEditor);